/**
 * 17/nov/2011 - fabio.melillo@gmail.com
 */
package org.unisannio.remote;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.unisannio.util.BroadcastRequest;
import org.unisannio.util.BroadcastResult;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.Images.Media;
import android.util.Base64;

/**
 * This class allows communication with other peers in the specialized broadcast mode
 * 
 * @author Fabio Melillo
 * 
 */
public class RemoteBroadcaster extends GenericRemote{

	public RemoteBroadcaster(Context context){
		super(context);
	}
	
	public RemoteBroadcaster(Context context, int port) {
		super(context, port);
	}
	
	/**
	 * Send the Broadcast to all the peers which can handle the action of the intent.
	 * The resultReceiver.onReceive will be called from the middleware at the end of the Broadcast
	 * @see <a href="http://developer.android.com/reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent, java.lang.String, android.content.BroadcastReceiver, android.os.Handler, int, java.lang.String, android.os.Bundle)
	 * ">Context.sendOrderedBroadcast()</a>
	 * 
	 * @param intent
	 * @param receiverPermission
	 * @param resultReceiver - your receiver, will be called asyncronically when results arrive
	 * @param scheduler - not managed in remote device
	 * @param initialCode
	 * @param initialData
	 * @param initialExtras
	 */
	public void sendRemoteOrderedBroadcast(Intent intent, String receiverPermission,
			BroadcastReceiver resultReceiver, Handler scheduler,
			int initialCode, String initialData, Bundle initialExtras) {
		
		//aggiungo il sender all'intent
		intent.putExtra(BroadcastContentPeer.ADDRESSKEY, broadcastContentPeer.getAddress().toString());
		initialExtras.putString(BroadcastContentPeer.ADDRESSKEY, broadcastContentPeer.getAddress().toString());

		BroadcastRequest broadcastReq = new BroadcastRequest(intent,
				receiverPermission, resultReceiver, scheduler, initialCode,
				initialData, initialExtras);
		broadcastContentPeer.send(broadcastReq,true);
	}

	/**
	 * Returns the bundle with the results to the caller
	 * 
	 * @param action - the interested action
	 * @param bundle - results
	 */
	public void returnRemoteResult(String action, Bundle bundle) {
		BroadcastResult resp=new BroadcastResult(action, bundle);
		String senderAddr=bundle.getString(BroadcastContentPeer.ADDRESSKEY);
		bundle.putString(BroadcastContentPeer.ADDRESSKEY, broadcastContentPeer.getAddress().toString());
		broadcastContentPeer.returnBroadcastResult(resp, senderAddr);
	}
	
	/**
	 * Converts an image file in an encoded string, ready for intent extra
	 * 
	 * @param file - the image
	 * @return the encoded string
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public String imgToString(File file) throws FileNotFoundException, IOException{
		final int maxpayloadsize=42000;
//		final int maxpayloadsize=15000;
		Bitmap captureBmp = Media.getBitmap(context.getContentResolver(), Uri.fromFile(file) ); 
		Bitmap resizedBitmap=Bitmap.createScaledBitmap(captureBmp, (int) (captureBmp.getWidth()*0.25), (int) (captureBmp.getHeight()*0.25),true);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
		byte[] buf = baos.toByteArray();
		int size=buf.length;
		int qual=100;
//		System.out.println("size:"+size+" qual:"+qual);
		while(size>maxpayloadsize){
			baos.reset();
			resizedBitmap.compress(Bitmap.CompressFormat.JPEG, qual, baos);
			buf = baos.toByteArray();
			size=buf.length;
			qual=qual-5;
//			System.out.println("size:"+size+" qual:"+qual);
		}
		String immagine=Base64.encodeToString(buf, Base64.DEFAULT);
		return immagine;
	}
	
	/**
	 * Decodes a String and saves the image in the file passed as argument.
	 * From this file is possible to read the jpg image later.
	 * 
	 * @param img the string passed through the intent
	 * @return the bitmap (.jpg) to show
	 * @throws IOException 
	 */
	public static Bitmap stringToBmpSaveInFile(String img, File filePic) throws IOException{
		byte[] buf=Base64.decode(img, Base64.DEFAULT);
		FileOutputStream fos=new FileOutputStream(filePic);
		Bitmap bm=BitmapFactory.decodeByteArray(buf, 0, buf.length);
		bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
		fos.flush();
		fos.close();
		return bm;
	}
	
	

}
